package com.ds.lens.data.common.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * describe:
 *
 * @author wangyiming
 * @date 2019/07/29
 */
public class APMMetricIdGenerator implements MetricIdGenerator {
    private Gson gson = new GsonBuilder().create();
    @Override
    public String generate(MetricId metricId) {
        String json = gson.toJson(metricId, MetricId.class);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(json.getBytes(StandardCharsets.UTF_8));
            byte[] md5bytes = md.digest();
            String md5code = new BigInteger(1, md5bytes).toString(16);
            while(md5code.length() < 32 ){
                md5code = "0" + md5code;
            }
            return md5code;
        } catch (NoSuchAlgorithmException e) {
            return json;
        }
    }
}
